iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
Mobile Development

Flutter - 從 Packages & Plugins 掌握原生系列 第 17

Day17 開發套件 - 實作BasicMessageChannel

  • 分享至 

  • xImage
  •  

用於雙向的單次訊息傳遞,包括發送訊息、接收訊息兩個功能

經過以上的實作,其實兩端的通訊步驟都差不多,首先在兩端建立想要Channel並指定名稱,且在兩端通道名稱需對應,傳送端對接收端發訊息來執行Channel的對應的動作(執行Native 端方法,或監聽Native 端訊息,亦或發送訊息至Native 端訊息),接收端建立完對應的Channel後要建立handler處理從傳送端來的訊息執行對應動作,並回傳結果

Flutter 端

新增BasicMessageChannel並指定名稱,且新增要從Flutter 端傳訊息給Native 端的方法,並回傳Native 端要回覆的訊息

lib/batterylevel.dart

	static const BasicMessageChannel _messageChannel =
      const BasicMessageChannel('chat_message', StringCodec());

  static Future<String> messageResponse(String message) async {
    final String response = await _messageChannel.send(message);
    return response;
  }

Native 端(Android):

android/.../BatterylevelPlugin.kt

    private lateinit var messageChannel: BasicMessageChannel<String>

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        //Added
        messageChannel = BasicMessageChannel(
            flutterPluginBinding.binaryMessenger,
            "chat_message",
            StringCodec.INSTANCE
        )
        messageChannel.setMessageHandler { message, reply ->
            val response = if(message.isNullOrEmpty()) "" else "Android 收到:$message"
            reply.reply(response)
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        //Added
        messageChannel.setMessageHandler(null)
    }

Native 端(iOS):

ios/Classes/RandomNumberStreamHandler.swift

public class SwiftBatterylevelPlugin: NSObject, FlutterPlugin {
    public static func register(with registrar: FlutterPluginRegistrar) {
				//Added
        let messageChannel = FlutterBasicMessageChannel(name: "chat_message", binaryMessenger: 			registrar.messenger(),codec: FlutterStringCodec.sharedInstance())
        
        messageChannel.setMessageHandler {
            (message: Any?, reply: FlutterReply) -> Void in
            reply((message as! String) != "" ? "iOS 收到:\(message as! String)" : "");
        }
    }
}

以上就完成運用Platform Channel來實作平台兩端的通訊了,[範例程式都在這](


上一篇
Day16 開發套件 - 實作EventChannel
下一篇
Day18 Plugin 從零開始到上架 01
系列文
Flutter - 從 Packages & Plugins 掌握原生30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言